﻿using CommunityToolkit.WinUI.Collections;

namespace DimensionsHelper.Client.WinUi.Models;

public class MessageModelSource : IIncrementalSource<MessageModel>
{
    private static readonly object Lock = new();


    internal List<MessageModel> Items { get; } = [];

    public async Task<IEnumerable<MessageModel>> GetPagedItemsAsync(int pageIndex, int pageSize,
        CancellationToken cancellationToken = default)
    {
        return await Task.Run(() =>
        {
            return Items.Skip(pageIndex * pageSize).Take(pageSize);
        }, cancellationToken);
    }


    public event Action<MessageModel>? ItemAdded;

    public event Action? Cleared;


    public void AddMessage(MessageModel messageModel)
    {
        lock (Lock)
        {
            Items.Add(messageModel);
            ItemAdded?.Invoke(messageModel);
        }
    }

    public void Clear()
    {
        lock (Lock)
        {
            bool isEmpty = Items.Count == 0;
            Items.Clear();

            if (!isEmpty)
            {
                Cleared?.Invoke();
            }
        }
    }
}